﻿using AutoMapper;
using DTcms.Core.Common.Emum;
using DTcms.Core.Common.Extensions;
using DTcms.Core.Common.Helper;
using DTcms.Core.DBFactory.Database;
using DTcms.Core.IServices;
using DTcms.Core.Model.Models;
using DTcms.Core.Model.ViewModels;
using Microsoft.EntityFrameworkCore;
using System.Linq.Expressions;

namespace DTcms.Core.Services
{
    /// <summary>
    /// 会员地址接口实现
    /// </summary>
    public class MemberAddressService : BaseService, IMemberAddressService
    {
        private readonly IMapper _mapper;
        public MemberAddressService(IMapper mapper, IDbContextFactory contentFactory) : base(contentFactory)
        {
            _mapper = mapper;
        }

        /// <summary>
        /// 根据条件获取一条记录
        /// </summary>
        public async Task<MemberAddressDto?> QueryAsync(Expression<Func<MemberAddressDto, bool>> funcWhere,
            WriteRoRead writeAndRead = WriteRoRead.Read)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库
            //联合查询重新组合
            var result = from a in _context.Set<MemberAddress>()
                         from u in _context.Set<ApplicationUser>().Where(u => u.Id == a.UserId)
                         select (new MemberAddressDto
                         {
                             Id = a.Id,
                             UserId = a.UserId,
                             UserName = u.UserName,
                             AcceptName = a.AcceptName,
                             Province = a.Province,
                             City = a.City,
                             Area = a.Area,
                             Address = a.Address,
                             Telphone = a.Telphone,
                             Mobile = a.Mobile,
                             Zip = a.Zip,
                             IsDefault = a.IsDefault,
                             AddTime = a.AddTime
                         });
            //加入查询条件并返回一条
            return await result.FirstOrDefaultAsync(funcWhere);
        }

        /// <summary>
        /// 根据条件获取列表
        /// </summary>
        public async Task<IEnumerable<MemberAddressDto>> QueryListAsync(int top, Expression<Func<MemberAddressDto, bool>> funcWhere,
            string orderBy, WriteRoRead writeAndRead = WriteRoRead.Read)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库
            //联合查询重新组合
            var result = from a in _context.Set<MemberAddress>()
                         from u in _context.Set<ApplicationUser>().Where(u => u.Id == a.UserId)
                         select (new MemberAddressDto
                         {
                             Id = a.Id,
                             UserId = a.UserId,
                             UserName = u.UserName,
                             AcceptName = a.AcceptName,
                             Province = a.Province,
                             City = a.City,
                             Area = a.Area,
                             Address = a.Address,
                             Telphone = a.Telphone,
                             Mobile = a.Mobile,
                             Zip = a.Zip,
                             IsDefault = a.IsDefault,
                             AddTime = a.AddTime
                         });
            result = result.Where(funcWhere);//加入查询条件
            result = LinqExtensions.OrderByBatch(result, orderBy);//调用Linq扩展类进行排序
            if (top > 0) result = result.Take(top);//等于0显示所有数据
            return await result.ToListAsync();
        }

        /// <summary>
        /// 根据条件获取分页列表
        /// </summary>
        public async Task<PaginationList<MemberAddressDto>> QueryPageAsync(int pageSize, int pageIndex,
            Expression<Func<MemberAddressDto, bool>> funcWhere, string orderBy, WriteRoRead writeAndRead = WriteRoRead.Read)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库
            //联合查询重新组合
            var result = from a in _context.Set<MemberAddress>()
                         from u in _context.Set<ApplicationUser>().Where(u => u.Id == a.UserId)
                         select (new MemberAddressDto
                         {
                             Id = a.Id,
                             UserId = a.UserId,
                             UserName = u.UserName,
                             AcceptName = a.AcceptName,
                             Province = a.Province,
                             City = a.City,
                             Area = a.Area,
                             Address = a.Address,
                             Telphone = a.Telphone,
                             Mobile = a.Mobile,
                             Zip = a.Zip,
                             IsDefault = a.IsDefault,
                             AddTime = a.AddTime
                         });
            result = result.Where(funcWhere);//加入查询条件
            result = LinqExtensions.OrderByBatch<MemberAddressDto>(result, orderBy);//调用Linq扩展类排序
            return await PaginationList<MemberAddressDto>.CreateAsync(pageIndex, pageSize, result);
        }

        /// <summary>
        /// 新增一条数据
        /// </summary>
        public async Task<bool> AddAsync(MemberAddress model, WriteRoRead writeAndRead = WriteRoRead.Write)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库

            model.AddTime = DateTime.Now;
            //如果当前设置为默认，则取消该用户下所有默认数据
            if (model.IsDefault == 1)
            {
                var list = await _context.Set<MemberAddress>().Where(x => x.UserId == model.UserId && x.IsDefault == 1).ToListAsync();
                foreach(var item in list)
                {
                    item.IsDefault = 0;
                }
                _context.Set<MemberAddress>().UpdateRange(list);
            }
            //添加新地址
            await _context.Set<MemberAddress>().AddAsync(model);
            //保存到数据库
            var result = await this.SaveAsync();
            return result;
        }

        /// <summary>
        /// 修改一条记录
        /// </summary>
        public async Task<bool> UpdateAsync(MemberAddress model, WriteRoRead writeAndRead = WriteRoRead.Write)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库

            //如果当前设置为默认，则取消该用户下所有默认数据
            if (model.IsDefault == 1)
            {
                var list = await _context.Set<MemberAddress>().Where(x => x.UserId == model.UserId && x.Id != model.Id && x.IsDefault == 1).ToListAsync();
                foreach (var item in list)
                {
                    item.IsDefault = 0;
                }
                _context.Set<MemberAddress>().UpdateRange(list);
            }
            _context.Set<MemberAddress>().Update(model);
            //全部提交保存
            return await this.SaveAsync();
        }

    }
}
